const RBAC = require('rbac-a');
const Provider = RBAC.providers.JsonProvider;

module.exports = function (options) {

    return async function (ctx, next) {
        const {module, controller, action} = koahub.common.getModuleControllerAction(ctx.path);


        const rules = await require('./rules')();

        // console.log(rules);

        RBAC.prototype.checkByCode = async function (user, code, module) {

            const Permission = koahub.model('admin/Permission');
            const entity = await Permission.findOne({code: code, module: module}).exec();
            if (entity) {
                koahub.logger.debug(`检查权限：id:${entity['id']},code:${entity['code']},title:${entity['title']},module:${entity['module']}`);
                const permissionId = entity['_id'].toString();
                return this.check(user, permissionId);
            }
            return 0;
        };

        //绑定上下文
        ctx.rbac = new RBAC({
            provider: new Provider(rules)
        });

        await next();
    };
};